<?php

/**
 * This is the model class for table "menu".
 *
 * The followings are the available columns in table 'menu':
 * @property string $id
 * @property string $root
 * @property string $lft
 * @property string $rgt
 * @property integer $level
 * @property string $name
 * @property string $description
 */
class ProductCategory extends CActiveRecord {

    const ADMIN_TREE_CONTAINER_ID = 'product_category_tree';

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return ProductCategory the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'product_category';
    }
  
    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE1: you should only define rules for those attributes that
        // will receive user inputs.
        // NOTE2: Remove ALL rules associated with the nested Behavior:
        // rgt,lft,root,level,id.
        return array(array('name', 'required'),
            array('name,alias', 'length', 'max' => 64), // The following rule is used by search().
            array('rank', 'numerical', 'min' => 0, 'max' => 20, 'integerOnly' => TRUE),
            array('imgId', 'safe'),
            // Please remove those attributes that should not be searched.
            array('name, description, alias', 'safe', 'on' => 'search'),);
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
                'page' => array(self::HAS_MANY, 'Page', 'menuId'),
                'avatar' => array(self::BELONGS_TO, 'FileImage', 'imgId'),     
                'products'=>array(self::HAS_MANY, 'Product', 'categoryId')
        );
        
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'name' => 'ProductCategory',
            'description' => 'Description',
        );
    }
    public function behaviors() {
        return array('NestedSetBehavior' => array('class' => 'ext.NestedSetBehavior', 'leftAttribute' => 'lft', 'rightAttribute' => 'rgt', 'levelAttribute' => 'level','hasManyRoots' => true));
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;
        $criteria->compare('name', $this->name, true);
        $criteria->compare('description', $this->description, true);

        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                ));
    }

    protected function afterDelete() {
        parent::afterDelete();
        // Remove related products
        
        Product::model()->updateAll(array('status'=>0), 'categoryId=:categoryId', array(':categoryId'=>$this->id));
    }
    
    /*
     * @param $appendNodeId id of category want to open instead of close, if it is children of some parent category
     * then the parents will be opened too, set null if don't want open any node
     */
    public function getTreeData($appendNodeId=null, $level=0, $begin=0, $categories=null){
        if(!$categories)
            $categories = ProductCategory::model()->findAll(array('order' => 'root,lft'));                
        $parentNeedAppand=false;
        $results=array();        
        $i=$begin;
        $total=count($categories);
        while($i<$total){
            $category=$categories[$i];
            if($category->level>=$level){
                $level=$category->level;
                $r=array();
                $r['text']=$category->name;
                $r['id']='node_'.$category->id;
                $r['hasChildren']=false;
                if($parentNeedAppand===false && $category->id==$appendNodeId){
                    $parentNeedAppand=true;
                }
                if(isset($categories[$i+1]) && $categories[$i+1]->level>$level){
                    $r['hasChildren']=true;
                    $ret=$this->getTreeData($appendNodeId, $level, $i+1, $categories);
                    $r['children']=$ret['nodes'];
                    if($parentNeedAppand===false && $ret['parentNeedAppand']===true){
                        $parentNeedAppand=true;
                    }
                    
                    if($ret['parentNeedAppand']){
                        $r['expanded']=true;
                    }
                    
                    $i=$ret['index'];
                }

                $results[]=$r;
            }else if($category->level<$level){
                return array(
                    'nodes'=>$results,
                    'parentNeedAppand'=>$parentNeedAppand,
                    'index'=>$i-1
                );
            }
            
            $i++;
        }
        
        return array(
            'nodes'=>$results,
            'index'=>$i
        );
                
    }
    
    public function getTreeDataAndExpandLevel($expandNodeId=null, $expandLevel=1, $level=0, $begin=0, $categories=null){
        if(!$categories)
            $categories = ProductCategory::model()->findAll(array('order' => 'root,lft'));                
                
        $parentNeedAppand=false;
        $results=array();        
        $i=$begin;
        $total=count($categories);
        while($i<$total){
            $category=$categories[$i];
            if($category->level>=$level){
                $level=$category->level;
                $r=array();
                
                $r['id']='node_'.$category->id;
                $r['hasChildren']=false;
                if($parentNeedAppand===false && $category->id==$expandNodeId){
                    $parentNeedAppand=true;
                }
                
                if($category->id==$expandNodeId){
                    $r['text']='<span class="file selected">'.$category->name.'</span>';
                }else{
                    $r['text']='<span class="file">'.$category->name.'</span>';
                }
                
                if($expandLevel==$category->level){
                    $r['expanded']=true;
                }
                if(isset($categories[$i+1]) && $categories[$i+1]->level>$level){
                    $r['hasChildren']=true;
                    
                    $r['text']='<span class="folder">'.$category->name.'</span>';
                    
                    $ret=$this->getTreeDataAndExpandLevel($expandNodeId, $expandLevel, $level, $i+1, $categories);
                    $r['children']=$ret['nodes'];
                    if($parentNeedAppand===false && $ret['parentNeedAppand']===true){
                        $parentNeedAppand=true;
                    }
                    
                    if($ret['parentNeedAppand']){
                        $r['expanded']=true;
                    }
                                        
                    $i=$ret['index'];
                }
                
                $r['htmlOptions']=array(
                    'class'=>'level_'.$category->level
                );
                
                $results[]=$r;
            }else if($category->level<$level){
                return array(
                    'nodes'=>$results,     
                    'parentNeedAppand'=>$parentNeedAppand,
                    'index'=>$i-1
                );
            }
            
            $i++;
        }
        
        return array(
            'nodes'=>$results,
            'index'=>$i
        );
                
    }
    
    public function getAllChildLeafCategoryIds($parentCategoryId){
        $categories = ProductCategory::model()->findAll(array('order' => 'root,lft'));
        
        $results=array();
        
        $level=99999;
        $begin=false;
        foreach($categories as $i=>$cat){
            if($cat->id==$parentCategoryId){
                $level=$cat->level;
                $begin=true;
                continue;
            }
            
            if($begin && $cat->level>$level){
                if(!isset($categories[$i+1])){
                    $results[]=$cat->id;
                }else{
                    if($categories[$i+1]->level<=$cat->level){
                        $results[]=$cat->id;
                    }
                }
            }else if($begin && $cat->level<=$level){
                break;
            }
        }
        
        return $results;
    }
    
}